use crate::movie::{MoviePath};
use movie::error::{Error, Result};
use std::{fs::OpenOptions, io, path::PathBuf};

pub fn loop_input() {
    loop {
        let mut path = String::new();
        let file_path = match io::stdin().read_line(&mut path) {
            Ok(bytes) if bytes != 0 && path.trim().eq_ignore_ascii_case("quit") => {
                println!("程序退出");
                break;
            }
            Ok(bytes) if bytes != 0 => path.trim().to_string(),
            Ok(_) => {
                println!("未输入任何内容，请重新输入");
                continue;
            }
            Err(e) => {
                println!("读取输入失败: {}", e);
                continue;
            }
        };

        let buf = PathBuf::from(file_path.clone());
        if !buf.exists() {
            eprintln!("错误: 文件不存在 - {}", file_path);
            continue;
        }
        match OpenOptions::new().read(true).open(&buf) {
            Ok(file) => {
                MoviePath::new(buf).read_txt_to_json(file);
            }
            Err(e) => {
                eprintln!("打开文件失败: {}", e);
            }
        }
    }
}

pub fn default_input() -> Result<()> {
    let mut path = String::new();
    let result = match io::stdin().read_line(&mut path) {
        Ok(bytes) if bytes != 0 => {
            let trimmed = path.trim();
            if trimmed.is_empty() {
                return Err(Error::Internal("输入路径为空".to_string()));
            }
            Ok(trimmed.to_string())
        }
        Ok(_) => Err(Error::Internal("未读取到任何内容".to_string())),
        Err(e) => Err(Error::Internal(format!("读取输入失败: {}", e))),
    };
    let file_path = result?.clone();
    let buf = PathBuf::from(file_path.clone());
    if !buf.exists() {
        return Err(Error::Internal(format!("错误: 文件不存在 - {}", file_path.clone())));
    }
    match OpenOptions::new().read(true).open(&buf) {
        Ok(file) => {
            MoviePath::new(buf).read_txt_to_json(file);
            Ok(())
        }
        Err(e) => Err(Error::Internal(format!("打开文件失败: {}", e))),
    }
}

pub fn change_txt_to_json(buf: PathBuf) -> Result<String> {
    if !buf.exists() {
        return Err(Error::Internal(format!("错误: 文件不存在 - {}", buf.to_string_lossy().clone())));
    }
    Ok(match OpenOptions::new().read(true).open(&buf) {
        Ok(file) => {
            MoviePath::new(buf.clone()).read_txt_to_json(file);
            buf.to_str().expect("路径包含非 UTF-8 字符").to_string()
        }
        Err(e) => return Err(Error::Internal(format!("打开文件失败: {}", e))),
    })
}